package net.jacqeush.mini.rpc.annotation.auto.register;


import net.jacqeush.mini.rpc.annotation.RpcService;
import net.jacqeush.mini.server.config.ProviderConfig;
import net.jacqeush.mini.server.config.RpcServerConfig;
import org.springframework.beans.factory.config.BeanDefinitionHolder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * @author Jacquesh
 * @version 1.0
 * @date 2020/10/21 20:53
 */

public class RpcByAnnotationStarter implements  Runnable {
    private int  port =8765;
    ClassLoader classLoader=this.getClass().getClassLoader();
    List<ProviderConfig> providerConfigs = new ArrayList<>();
 private    Set<BeanDefinitionHolder> beanDefinitionHolders;

    public RpcByAnnotationStarter(Set<BeanDefinitionHolder> beanDefinitionHolders) {
        this.beanDefinitionHolders = beanDefinitionHolders;
    }

    public void  starter(){
     // 每一个具体的服务提供者的配置类
     beanDefinitionHolders.forEach((beanDefinitionHolder)->{
         try {

         beanDefinitionHolder.getBeanDefinition().getBeanClassName();
          Class<?> clazz= classLoader.loadClass(beanDefinitionHolder.getBeanDefinition().getBeanClassName());

             List<Class<?>> clazzs= Arrays.asList(clazz.getInterfaces());
             clazzs.forEach((cl)->{

                     try {
                         ProviderConfig providerConfig = new ProviderConfig();
                         providerConfig.setInterfaceClass(cl.getName());
                         providerConfig.setRef(clazz.newInstance());
                         providerConfigs.add(providerConfig);
                     }  catch (IllegalAccessException | InstantiationException e) {
                         e.printStackTrace();
                     }



             });

         } catch (ClassNotFoundException e) {
             e.printStackTrace();
         }
     });
     RpcServerConfig rpcServerConfig = new RpcServerConfig(providerConfigs);
     rpcServerConfig.setPort(port);
     rpcServerConfig.exporter();
  }


    @Override
    public void run() {
        this.starter();
    }
}
